package com.meilai.project.service.business.customer.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.meilai.project.constant.BossUserEnum;
import com.meilai.project.constant.MaintenanceStaffChangeEnum;
import com.meilai.project.entity.business.customer.CustomerInfo;
import com.meilai.project.entity.business.customer.CustomerMaintainUserRecord;
import com.meilai.project.exception.CommonException;
import com.meilai.project.mapper.business.customer.CustomerApplyFollowRecordMapper;
import com.meilai.project.mapper.business.customer.CustomerInfoMapper;
import com.meilai.project.service.business.customer.CustomerInfoService;
import com.meilai.project.service.business.customer.CustomerMaintainUserRecordService;
import com.meilai.project.service.business.customer.CustomerPoolService;
import com.meilai.project.vo.business.customer.BaseCustomerPoolVO;
import com.meilai.project.vo.business.customer.CheckPageCustomerVO;
import com.meilai.project.vo.business.customer.PublicSeaVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xhy
 * @since 2022-09-09
 */
@Service
public class CustomerPoolServiceImpl implements CustomerPoolService {
    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private CustomerInfoService customerInfoService;

    @Autowired
    private CustomerApplyFollowRecordMapper customerApplyFollowRecordMapper;

    @Autowired
    private CustomerMaintainUserRecordService customerMaintainUserRecordService;

    public void handleList(List<? extends BaseCustomerPoolVO> list) {
        // 获取boss_ids
        List<Long> boss_ids = new ArrayList<>(Arrays.asList(BossUserEnum.values())).stream().map(BossUserEnum::getId).collect(Collectors.toList());
        list.forEach(item -> {
            if (boss_ids.contains(item.getPerson_in_charge_id())) {
                item.setType(1);
            } else {
                item.setType(2);
            }
        });
    }

    @Override
    public Page<BaseCustomerPoolVO> selectPage(Integer current_page, Integer page_size, String name, Long industry_id, Integer type) {
        Page<BaseCustomerPoolVO> page = new Page<>(current_page, page_size);
        // 获取boss_ids
        List<Long> boss_ids = new ArrayList<>(Arrays.asList(BossUserEnum.values())).stream().map(BossUserEnum::getId).collect(Collectors.toList());
        List<BaseCustomerPoolVO> records = customerInfoMapper.selectPage(page, name, industry_id, boss_ids, type);
        handleList(records);
        page.setRecords(records);
        return page;
    }

    @Override
    public Page<CheckPageCustomerVO> selectCheckRecordPage(Integer current_page, Integer page_size, String name, Long industry_id, Long apply_user_id, Integer type, Integer status) {
        Page<CheckPageCustomerVO> page = new Page<>(current_page, page_size);
        // 获取boss_ids
        List<Long> boss_ids = new ArrayList<>(Arrays.asList(BossUserEnum.values())).stream().map(BossUserEnum::getId).collect(Collectors.toList());
        List<CheckPageCustomerVO> records = customerApplyFollowRecordMapper.selectCheckRecordPage(page, name, industry_id, apply_user_id, type, boss_ids, status);
        handleList(records);
        page.setRecords(records);
        return page;
    }

    @Override
    public Page<PublicSeaVO> selectPublicSeaPage(Integer current_page, Integer page_size, String name, Long industry_id, Integer type) {
        Page<PublicSeaVO> page = new Page<>(current_page, page_size);
        // 获取boss_ids
        List<Long> boss_ids = new ArrayList<>(Arrays.asList(BossUserEnum.values())).stream().map(BossUserEnum::getId).collect(Collectors.toList());
        List<PublicSeaVO> records = customerInfoMapper.selectPublicSeaPage(page, name, industry_id, boss_ids, type);
        handleList(records);
        page.setRecords(records);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean distribute(Long customer_id, Long user_id) {
        CustomerInfo customerInfo = customerInfoMapper.selectById(customer_id);
        if (customerInfo == null) {
            throw new CommonException("数据不存在");
        }
        CustomerMaintainUserRecord customerMaintainUserRecord = new CustomerMaintainUserRecord();
        customerMaintainUserRecord.setCustomer_id(customer_id);
        customerMaintainUserRecord.setUpdate_time(LocalDateTime.now());
        customerMaintainUserRecord.setOld_maintain_user_id(customerInfo.getMaintenance_staff_id());
        customerMaintainUserRecord.setNew_maintain_user_id(user_id);
        customerMaintainUserRecord.setType(MaintenanceStaffChangeEnum.KE_HU_CHI_ZHI_PAI.getId());
        return customerMaintainUserRecordService.save(customerMaintainUserRecord)
                && customerInfoService.update(Wrappers.<CustomerInfo>lambdaUpdate().set(CustomerInfo::getMaintenance_staff_id, user_id).set(CustomerInfo::getMaintain_user_record_id, customerMaintainUserRecord.getId()).eq(CustomerInfo::getId, customer_id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean relieve(Long customer_id, Integer type) {
        CustomerInfo customerInfo = customerInfoMapper.selectById(customer_id);
        if (customerInfo == null) {
            throw new CommonException("数据不存在");
        }
        CustomerMaintainUserRecord customerMaintainUserRecord = new CustomerMaintainUserRecord();
        customerMaintainUserRecord.setCustomer_id(customer_id);
        customerMaintainUserRecord.setUpdate_time(LocalDateTime.now());
        customerMaintainUserRecord.setOld_maintain_user_id(customerInfo.getMaintenance_staff_id());
        customerMaintainUserRecord.setNew_maintain_user_id(null);
        customerMaintainUserRecord.setType(type == 1 ? MaintenanceStaffChangeEnum.KE_HU_CHI_JIE_CHU.getId() : MaintenanceStaffChangeEnum.ZI_JI_JIE_CHU.getId());
        return customerMaintainUserRecordService.save(customerMaintainUserRecord)
                && customerInfoService.update(Wrappers.<CustomerInfo>lambdaUpdate().set(CustomerInfo::getMaintenance_staff_id, null).set(CustomerInfo::getMaintain_user_record_id, customerMaintainUserRecord.getId()).eq(CustomerInfo::getId, customer_id));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateCanAssign(Long customer_id) {
        CustomerInfo customerInfo = customerInfoMapper.selectById(customer_id);
        if (customerInfo == null) {
            throw new CommonException("数据不存在");
        }
        // 获取boss_ids
        List<Long> boss_ids = new ArrayList<>(Arrays.asList(BossUserEnum.values())).stream().map(BossUserEnum::getId).collect(Collectors.toList());
        if (customerInfo.getMaintenance_staff_id() != null && !boss_ids.contains(customerInfo.getMaintenance_staff_id())) {// 如果当前维护人不是可分配的客户
            CustomerMaintainUserRecord customerMaintainUserRecord = new CustomerMaintainUserRecord();
            customerMaintainUserRecord.setCustomer_id(customer_id);
            customerMaintainUserRecord.setUpdate_time(LocalDateTime.now());
            customerMaintainUserRecord.setOld_maintain_user_id(customerInfo.getMaintenance_staff_id());
            customerMaintainUserRecord.setNew_maintain_user_id(null);
            customerMaintainUserRecord.setType(MaintenanceStaffChangeEnum.GAI_BIAN_FENG_PEI_SHU_XING.getId());
            customerMaintainUserRecordService.save(customerMaintainUserRecord);
            customerInfoService.update(Wrappers.<CustomerInfo>lambdaUpdate()
                    .set(CustomerInfo::getMaintenance_staff_id, null)
                    .set(CustomerInfo::getMaintain_user_record_id, customerMaintainUserRecord.getId())
                    .eq(CustomerInfo::getId, customer_id));
        }
        return customerInfoService.update(Wrappers.<CustomerInfo>lambdaUpdate().set(CustomerInfo::getCan_assign, !customerInfo.getCan_assign()).eq(CustomerInfo::getId, customer_id));
    }

    @Override
    public Boolean checkCustomerMaintain(Long customer_id) {
        CustomerInfo customerInfo = customerInfoMapper.selectById(customer_id);
        if (customerInfo == null) {
            throw new CommonException("数据不存在");
        }
        // 获取boss_ids
        List<Long> boss_ids = new ArrayList<>(Arrays.asList(BossUserEnum.values())).stream().map(BossUserEnum::getId).collect(Collectors.toList());
        return customerInfo.getMaintenance_staff_id() == null || boss_ids.contains(customerInfo.getMaintenance_staff_id());
    }
}
